/**
 * 小红书自动发布 Electron 模块
 * 
 * 包含完整的数据库功能和自动化发布逻辑
 * 专门为 Electron 环境设计
 */

const { BrowserWindow, session, ipcMain } = require('electron');
const path = require('path');
const fs = require('fs');
const Database = require('./database');

class XiaohongshuElectronPublisher {
  constructor(options = {}) {
    this.options = {
      // 数据目录配置
      dataDir: options.dataDir || this.getDefaultDataDir(),
      // 主窗口引用
      mainWindow: options.mainWindow || null,
      // 是否自动初始化数据库
      autoInitDB: options.autoInitDB !== false,
      // 是否自动注册 IPC 处理器
      autoRegisterIPC: options.autoRegisterIPC !== false,
      // 无头模式
      headless: options.headless || false,
      // 自定义配置
      ...options
    };
    
    this.db = null;
    this.xiaohongshuWindow = null;
    this.publishWindow = null;
    this.isInitialized = false;
    
    // 自动初始化
    if (this.options.autoInitDB) {
      this.initDatabase();
    }
    
    if (this.options.autoRegisterIPC) {
      try {
        this.registerIPCHandlers();
      } catch (error) {
        console.warn('⚠️ IPC 处理器注册失败:', error.message);
      }
    }
  }

  /**
   * 初始化数据库
   */
  async initDatabase() {
    try {
      // 确保数据目录存在
      if (!fs.existsSync(this.options.dataDir)) {
        fs.mkdirSync(this.options.dataDir, { recursive: true });
      }
      
      this.db = new Database(this.options.dataDir);
      await this.db.init();
      
      console.log('✅ 小红书发布器数据库初始化成功');
      this.isInitialized = true;
    } catch (error) {
      console.error('❌ 小红书发布器数据库初始化失败:', error);
      throw error;
    }
  }

  /**
   * 注册 IPC 处理器
   */
  registerIPCHandlers() {
    // 检查是否在 Electron 环境中
    if (typeof ipcMain === 'undefined' || !ipcMain || !ipcMain.handle) {
      console.warn('⚠️ 不在 Electron 环境中，跳过 IPC 处理器注册');
      return;
    }
    
    // 创建小红书登录窗口
    ipcMain.handle('xiaohongshu-open-login', () => {
      return this.openXiaohongshuLogin();
    });

    // 获取 cookies
    ipcMain.handle('xiaohongshu-get-cookies', async () => {
      return this.getCookies();
    });

    // 打开小红书发布页面
    ipcMain.handle('xiaohongshu-open-publish', async (event, contentData) => {
      return this.openXiaohongshuPublish(contentData);
    });

    // 获取账号信息
    ipcMain.handle('xiaohongshu-get-account-by-account-id', async (event, accountId) => {
      return this.getAccountByAccountId(accountId);
    });

    // 保存账号
    ipcMain.handle('xiaohongshu-save-account', async (event, accountData) => {
      return this.saveAccount(accountData);
    });

    // 获取所有账号
    ipcMain.handle('xiaohongshu-get-accounts', async () => {
      return this.getAccounts();
    });

    // 删除账号
    ipcMain.handle('xiaohongshu-delete-account-by-account-id', async (event, accountId) => {
      return this.deleteAccountByAccountId(accountId);
    });

    // 保存发布记录
    ipcMain.handle('xiaohongshu-save-publish-record', async (event, recordData) => {
      return this.savePublishRecord(recordData);
    });

    // 更新发布记录状态
    ipcMain.handle('xiaohongshu-update-publish-record-status', async (event, recordId, statusData) => {
      return this.updatePublishRecordStatus(recordId, statusData);
    });

    // 获取发布记录
    ipcMain.handle('xiaohongshu-get-publish-records', async () => {
      return this.getPublishRecords();
    });

    // 通过 account_id 获取发布记录
    ipcMain.handle('xiaohongshu-get-publish-records-by-account-id', async (event, accountId) => {
      return this.getPublishRecordsByAccountId(accountId);
    });

    // 通过 id 获取单个发布记录
    ipcMain.handle('xiaohongshu-get-publish-record-by-id', async (event, recordId) => {
      return this.getPublishRecordById(recordId);
    });

    // 验证cookie有效性
    ipcMain.handle('xiaohongshu-validate-account-cookies', async (event, accountId) => {
      return this.validateAccountCookies(accountId);
    });

    // 关闭发布窗口
    ipcMain.handle('xiaohongshu-close-publish-window', () => {
      return this.closePublishWindow();
    });

    console.log('✅ 小红书发布器 IPC 处理器注册完成');
  }

  /**
   * 创建小红书登录窗口
   */
  openXiaohongshuLogin() {
    try {
      this.xiaohongshuWindow = new BrowserWindow({
        width: 1000,
        height: 700,
        webPreferences: {
          nodeIntegration: false,
          contextIsolation: true
        },
        title: '小红书登录',
        parent: this.options.mainWindow,
        modal: true,
        show: !this.options.headless
      });

      this.xiaohongshuWindow.loadURL('https://creator.xiaohongshu.com/');

      this.xiaohongshuWindow.on('closed', () => {
        this.xiaohongshuWindow = null;
      });

      return { success: true };
    } catch (error) {
      console.error('打开小红书登录窗口失败:', error);
      return { success: false, error: error.message };
    }
  }

  /**
   * 获取 Cookies
   */
  async getCookies() {
    try {
      const cookies = await session.defaultSession.cookies.get({
        domain: '.xiaohongshu.com'
      });
      return { success: true, data: cookies };
    } catch (error) {
      console.error('获取 cookies 失败:', error);
      return { success: false, error: error.message };
    }
  }

  /**
   * 打开小红书发布页面并执行自动化
   */
  async openXiaohongshuPublish(contentData) {
    try {
      // 获取账号的 cookies (通过account_id字段查找)
      const account = await this.db.getAccountByAccountId(contentData.account_id);
      if (!account) {
        return { success: false, error: '账号不存在' };
      }

      // 创建发布窗口
      this.publishWindow = new BrowserWindow({
        width: 1200,
        height: 800,
        webPreferences: {
          nodeIntegration: false,
          contextIsolation: true,
          preload: this.getPreloadScript(),
          // webSecurity: false
        },
        title: '小红书发布页面',
        parent: this.options.mainWindow,
        modal: false,
        show: !this.options.headless,
      });

      // 设置 cookies
      if (account.cookies && account.cookies.length > 0) {
        for (const cookie of account.cookies) {
          try {
            await session.defaultSession.cookies.set({
              url: 'https://creator.xiaohongshu.com',
              name: cookie.name,
              value: cookie.value,
              domain: cookie.domain || '.xiaohongshu.com',
              path: cookie.path || '/',
              secure: cookie.secure === true,
              httpOnly: cookie.httpOnly === true,
              expirationDate: cookie.expirationDate
            });
          } catch (error) {
            console.warn('设置 cookie 失败:', error);
          }
        }
      }

      // 监听窗口关闭事件
      this.publishWindow.on('closed', () => {
        this.publishWindow = null;
        console.log('📱 发布窗口已关闭');
      });

      // 加载小红书发布页面
      this.publishWindow.loadURL('https://creator.xiaohongshu.com');

      // 等待页面加载完成后注入脚本
      this.publishWindow.webContents.on('did-finish-load', async () => {
        // 设置与主窗口相同的User-Agent
        await this.publishWindow.webContents.setUserAgent(
          this.options.mainWindow.webContents.getUserAgent()
        );
        try {
          this.publishWindow.webContents.openDevTools({ mode: 'right' });
          console.log('📝 注入 ContentFiller 类...');
          
          // 读取 content-filler.js 文件
          const contentFillerPath = this.getContentFillerPath();
          const contentFillerScript = fs.readFileSync(contentFillerPath, 'utf8');
          
          await this.publishWindow.webContents.executeJavaScript(`
            // 注入 ContentFiller 类
            ${contentFillerScript}
            
            // 创建内容填写器实例，传递 contentData
            const contentFiller = new ContentFiller(${JSON.stringify(contentData)});
            
            // 执行自动化内容填写流程
            contentFiller.execute().then(result => {
              console.log('🎉 自动化内容填写完成！', result);
            }).catch(error => {
              console.error('自动化内容填写失败:', error);
            });
          `);
          
        } catch (error) {
          console.error('注入脚本失败:', error);
        }
      });

      return { success: true, message: '已打开小红书发布页面，正在自动填写内容...' };
    } catch (error) {
      console.error('打开发布页面失败:', error);
      return { success: false, error: error.message };
    }
  }

  /**
   * 关闭发布窗口
   */
  closePublishWindow() {
    try {
      if (this.publishWindow && !this.publishWindow.isDestroyed()) {
        this.publishWindow.close();
        return { success: true };
      }
      return { success: false, error: '发布窗口不存在或已关闭' };
    } catch (error) {
      console.error('关闭发布窗口失败:', error);
      return { success: false, error: error.message };
    }
  }

  /**
   * 验证账号cookie有效性
   */
  async validateAccountCookies(accountId) {
    try {
      console.log(`🔍 开始验证账号 ${accountId} 的cookie有效性...`);
      
      // 获取账号信息
      const accountResult = await this.db.getAccountByAccountId(accountId);
      if (!accountResult) {
        return {
          success: false,
          valid: false,
          error: '账号不存在',
          errorType: 'ACCOUNT_NOT_FOUND'
        };
      }
      
      if (!accountResult.cookies || accountResult.cookies.length === 0) {
        return {
          success: false,
          valid: false,
          error: '账号没有保存cookie',
          errorType: 'NO_COOKIES'
        };
      }
      
      console.log(`📝 账号 ${accountId} 有 ${accountResult.cookies.length} 个cookie`);
      
      // 执行cookie验证
      const validationResult = await this.validateCookiesWithBrowser(accountResult.cookies);
      
      // 更新数据库中的验证状态
      try {
        await this.db.updateAccountValidationStatus(accountId, validationResult.valid);
      } catch (dbError) {
        console.warn('⚠️ 更新数据库验证状态失败:', dbError);
      }
      
      console.log(`✅ 账号 ${accountId} cookie验证完成，结果: ${validationResult.valid ? '有效' : '无效'}`);
      
      return {
        success: true,
        valid: validationResult.valid,
        error: validationResult.error,
        errorType: validationResult.errorType,
        finalUrl: validationResult.finalUrl,
        account_id: accountId,
        account_name: accountResult.name,
        validated_at: new Date().toISOString()
      };
      
    } catch (error) {
      console.error(`❌ 验证账号 ${accountId} cookie失败:`, error);
      return {
        success: false,
        valid: false,
        error: error.message,
        errorType: 'VALIDATION_ERROR',
        account_id: accountId
      };
    }
  }

  /**
   * 使用BrowserWindow验证cookie的核心方法
   */
  async validateCookiesWithBrowser(cookies) {
    return new Promise((resolve) => {
      console.log('🌐 创建验证窗口...');
      
      // 创建一个隐藏的浏览器窗口用于验证
      const validationWindow = new BrowserWindow({
        width: 1200,
        height: 800,
        show: false, // 隐藏窗口
        webSecurity: true,
        nodeIntegration: false,
        contextIsolation: true
      });
      
      // 设置超时保护
      const timeout = setTimeout(() => {
        console.log('⏰ 验证超时，关闭窗口');
        if (!validationWindow.isDestroyed()) {
          validationWindow.close();
        }
        resolve({
          valid: false,
          error: '验证超时',
          errorType: 'TIMEOUT'
        });
      }, 30000); // 30秒超时
      
      // 窗口关闭时清理
      validationWindow.on('closed', () => {
        clearTimeout(timeout);
      });
      
      // 设置cookie到session
      const session = validationWindow.webContents.session;
      
      console.log(`📝 开始设置 ${cookies.length} 个cookie...`);
      
      // 并行设置所有cookie
      const setCookiePromises = cookies.map(cookie => {
        return session.cookies.set({
          url: 'https://creator.xiaohongshu.com',
          name: cookie.name,
          value: cookie.value,
          domain: cookie.domain || '.xiaohongshu.com',
          path: cookie.path || '/',
          secure: cookie.secure !== false,
          httpOnly: cookie.httpOnly !== false,
          expirationDate: cookie.expirationDate
        }).catch(err => {
          console.warn(`⚠️ 设置cookie ${cookie.name} 失败:`, err);
        });
      });
      
      Promise.all(setCookiePromises).then(() => {
        console.log('✅ Cookie设置完成，开始访问小红书创作者中心...');
        
        // 监听页面加载完成
        validationWindow.webContents.once('did-finish-load', () => {
          const currentUrl = validationWindow.webContents.getURL();
          console.log(`📍 最终页面URL: ${currentUrl}`);
          
          clearTimeout(timeout);
          
          // 判断是否成功进入创作者中心
          if (currentUrl.includes('creator.xiaohongshu.com/creator')) {
            console.log('✅ Cookie有效：成功进入创作者中心');
            resolve({
              valid: true,
              finalUrl: currentUrl
            });
          } else if (currentUrl.includes('login') || currentUrl.includes('signin') || currentUrl.includes('passport')) {
            console.log('❌ Cookie无效：被重定向到登录页面');
            resolve({
              valid: false,
              error: '重定向到登录页面',
              errorType: 'REDIRECT_TO_LOGIN',
              finalUrl: currentUrl
            });
          } else {
            console.log('⚠️ Cookie状态不明：未知页面');
            resolve({
              valid: false,
              error: `未知页面: ${currentUrl}`,
              errorType: 'UNKNOWN_PAGE',
              finalUrl: currentUrl
            });
          }
          
          // 关闭验证窗口
          if (!validationWindow.isDestroyed()) {
            validationWindow.close();
          }
        });
        
        // 监听导航错误
        validationWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
          console.error('❌ 页面加载失败:', errorDescription);
          clearTimeout(timeout);
          
          resolve({
            valid: false,
            error: `页面加载失败: ${errorDescription}`,
            errorType: 'LOAD_FAILED',
            finalUrl: validatedURL
          });
          
          if (!validationWindow.isDestroyed()) {
            validationWindow.close();
          }
        });
        
        // 开始访问小红书创作者中心
        console.log('🚀 开始访问: https://creator.xiaohongshu.com/creator');
        validationWindow.loadURL('https://creator.xiaohongshu.com/creator').catch(err => {
          console.error('❌ 加载URL失败:', err);
          clearTimeout(timeout);
          
          resolve({
            valid: false,
            error: `加载URL失败: ${err.message}`,
            errorType: 'URL_LOAD_ERROR'
          });
          
          if (!validationWindow.isDestroyed()) {
            validationWindow.close();
          }
        });
        
      }).catch(cookieError => {
        console.error('❌ 设置cookie失败:', cookieError);
        clearTimeout(timeout);
        
        resolve({
          valid: false,
          error: `设置cookie失败: ${cookieError.message}`,
          errorType: 'COOKIE_SET_ERROR'
        });
        
        if (!validationWindow.isDestroyed()) {
          validationWindow.close();
        }
      });
    });
  }

  // ==================== 数据库操作方法 ====================

  /**
   * 获取账号信息
   */
  async getAccountByAccountId(accountId) {
    try {
      const account = await this.db.getAccountByAccountId(accountId);
      return { success: true, data: account };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  /**
   * 保存账号
   */
  async saveAccount(accountData) {
    try {
      const result = await this.db.saveAccount(accountData);
      return { success: true, data: result };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  /**
   * 获取所有账号
   */
  async getAccounts() {
    try {
      const accounts = await this.db.getAccounts();
      return { success: true, data: accounts };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  /**
   * 删除账号
   */
  async deleteAccountByAccountId(accountId) {
    try {
      await this.db.deleteAccountByAccountId(accountId);
      return { success: true };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  /**
   * 保存发布记录
   */
  async savePublishRecord(recordData) {
    try {
      const result = await this.db.savePublishRecord(recordData);
      return { success: true, data: result };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  /**
   * 更新发布记录状态
   */
  async updatePublishRecordStatus(recordId, statusData) {
    try {
      const result = await this.db.updatePublishRecordStatus(recordId, statusData);
      return { success: true, data: result };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  /**
   * 获取发布记录
   */
  async getPublishRecords() {
    try {
      const records = await this.db.getPublishRecords();
      return { success: true, data: records };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  /**
   * 通过 account_id 获取发布记录
   */
  async getPublishRecordsByAccountId(accountId) {
    try {
      const records = await this.db.getPublishRecordsByAccountId(accountId);
      return { success: true, data: records };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  /**
   * 通过 id 获取单个发布记录
   */
  async getPublishRecordById(recordId) {
    try {
      const record = await this.db.getPublishRecordById(recordId);
      return { success: true, data: record };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  /**
   * 关闭资源
   */
  async close() {
    if (this.db) {
      this.db.close();
    }
    
    if (this.xiaohongshuWindow) {
      this.xiaohongshuWindow.close();
    }

    if (this.publishWindow) {
      this.publishWindow.close();
    }
  }

  /**
   * 获取数据库实例（供外部使用）
   */
  getDatabase() {
    return this.db;
  }

  /**
   * 检查是否已初始化
   */
  isReady() {
    return this.isInitialized && this.db !== null;
  }

  /**
   * 获取默认数据目录
   */
  getDefaultDataDir() {
    const { app } = require('electron');
    
    if (app && app.isPackaged) {
      // 打包环境：使用用户数据目录
      return path.join(app.getPath('userData'), 'xiaohongshu-data');
    } else {
      // 开发环境：使用项目目录
      return path.join(__dirname, '..', 'data');
    }
  }

  /**
   * 获取预加载脚本路径
   */
  getPreloadScript() {
    const { app } = require('electron');
    
    if (app && app.isPackaged) {
      // 打包环境
      return path.join(app.getAppPath(), 'xiaohongshu-electron-publisher', 'lib', 'preload.js');
    } else {
      // 开发环境
      return path.join(__dirname, 'preload.js');
    }
  }

  /**
   * 获取content-filler.js路径
   */
  getContentFillerPath() {
    const { app } = require('electron');
    
    if (app && app.isPackaged) {
      // 打包环境
      return path.join(app.getAppPath(), 'xiaohongshu-electron-publisher', 'lib', 'content-filler.js');
    } else {
      // 开发环境
      return path.join(__dirname, 'content-filler.js');
    }
  }
}

module.exports = XiaohongshuElectronPublisher;
